package com.polaris.live.floating

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.PixelFormat
import android.os.Build
import android.view.Gravity
import android.view.WindowManager
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.ScreenUtils
import com.polaris.live.App
import com.polaris.live.common.cacha.CacheUtil
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.im.sfs.bean.live.SendLiveMessage
import com.polaris.live.popup.party.PartyHangUpDialog
import com.polaris.live.ui.party.widget.seat.PartyStreamProxy
import com.polaris.live.utils.XPopupUtils
import kotlinx.coroutines.launch

/**
 * FloatingWindowManager
 *
 * @author Created by 天晴 on 2024/11/18 16:32
 * @since 1.0.0
 **/
@SuppressLint("StaticFieldLeak")
object FloatingWindowManager {

    private var mFloatView: FloatingView? = null
    private var mWindowManager: WindowManager? = null
    private var mFloatingService: FloatingService? = null

    private var mLaunchActivity: Activity? = null //正在回到应用
    private var mLaunchClose = false //正在回到应用,是否是点击的close

    private var mFloatingViewTouchListener: FloatingViewTouchListener? = null

    /**
     * 只作为销毁小窗前临时保存历史消息  进入房间后销毁
     */
    private var mRoomId: String? = null //房间Id
    private var mMessageList: MutableList<SendLiveMessage>? = null //消息历史
    private var mPartyStreamProxy: PartyStreamProxy? = null  //推拉流管理

    fun putMessage(roomId: String, mPartyStreamProxy: PartyStreamProxy, messageList: MutableList<SendLiveMessage>) {
        this.mRoomId = roomId
        this.mPartyStreamProxy = mPartyStreamProxy
        this.mMessageList = messageList
    }

    fun getMessage(roomId: String?): MutableList<SendLiveMessage>? {
        return if (this.mRoomId == roomId && mMessageList != null) {
            val list = mMessageList
            this.mRoomId = null
            this.mMessageList = null
            list
        } else {
            this.mRoomId = null
            this.mMessageList = null
            null
        }
    }

    fun getPartyStreamProxy(roomId: String?): PartyStreamProxy? {
        return if (this.mRoomId == roomId && mPartyStreamProxy != null) {
            val partyStreamProxy = mPartyStreamProxy
            this.mPartyStreamProxy = null
            partyStreamProxy
        } else {
            mPartyStreamProxy?.destroyStreams()
            this.mPartyStreamProxy = null
            null
        }
    }

    /**
     * 是否小窗
     */
    fun isMinimize(): Boolean {
        return mFloatingService != null
    }

    fun showFloatingWindow(floatingService: FloatingService) {
        this.mFloatingService = floatingService
        if (mFloatView != null || !AppUtils.isAppForeground()) {
            return
        }

        addView()
    }

    private fun addView() {
        val context = App.getAppContext()
        mWindowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        mFloatView = FloatingView(context, null)
        mFloatView?.clickListener {
            if (mFloatingService?.getOwnSeat() != null) { //自己在座位
                if (!AppUtils.isAppForeground()) {
                    val topContext = ViewUtils.getAliveTopActivity()
                    if (topContext != null) {
                        val packageName = topContext.packageName
                        val intent = topContext.packageManager.getLaunchIntentForPackage(packageName)?.apply {
                            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
                        }
                        if (intent != null) {
                            topContext.startActivity(intent)
                            mLaunchActivity = topContext
                            mLaunchClose = true
                        }
                    }
                } else {
                    ViewUtils.getAliveTopActivity()?.let { ac ->
                        XPopupUtils.showPopup(PartyHangUpDialog(ac) {
                            onDestroyed()
                        }, {
                            this.isViewMode(false)
                        })
                    }
                }
            } else {
                onDestroyed()
            }

        }
        mFloatView?.setImage(mFloatingService?.getRoomCover())
        val adder = CacheUtil.getFloatingViewAddrFromKV()
        var x = adder[0]
        var y = adder[1]

        val type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
        } else {
            WindowManager.LayoutParams.TYPE_PHONE
        }

        val params = WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            type,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
            PixelFormat.TRANSLUCENT
        )
        params.gravity = Gravity.TOP or Gravity.START
        val maxWidth = ScreenUtils.getAppScreenWidth() - 56.autoDp
        if (x > maxWidth) {
            x = maxWidth
        }
        val maxHeight = ScreenUtils.getAppScreenHeight() - 67.autoDp
        if (y > maxHeight) {
            y = maxHeight
        }
        if (y < 0) {
            y = 0
        }
        params.x = x
        params.y = y
        mFloatingViewTouchListener = FloatingViewTouchListener(params, mWindowManager!!, {
            if (!AppUtils.isAppForeground()) {
                val topContext = ViewUtils.getAliveTopActivity()
                if (topContext != null) {
                    val packageName = topContext.packageName
                    val intent = topContext.packageManager.getLaunchIntentForPackage(packageName)?.apply {
                        flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
                    }
                    if (intent != null) {
                        topContext.startActivity(intent)
                        removeFloatingWindow()
                        mLaunchActivity = topContext
                    }
                }
            } else {
                mFloatingService?.recoverLive()
            }
        }) {
            mFloatView?.setType(it)
        }

        mFloatView?.setOnTouchListener(mFloatingViewTouchListener)

        mWindowManager?.addView(mFloatView, params)
        CacheUtil.saveFloatingViewAddr(x, y)
    }

    /**
     * 更新显示方向 0竖向  1横向
     */
    fun updateOrientation(orientation: Int) {
        mFloatView?.let {
            mFloatingViewTouchListener?.updataOrientation(it, orientation)
        }
    }

    /**
     * 回到应用 回到直播间
     */
    fun resumeActivity(activity: Activity) {
        if (activity == mLaunchActivity) {
            if (mLaunchClose) {
                ViewUtils.getAliveTopActivity()?.let { ac ->
                    XPopupUtils.showPopup(PartyHangUpDialog(ac) {
                        onDestroyed()
                    }, {
                        this.isViewMode(false)
                    })
                }
                mLaunchActivity = null
                mLaunchClose = false
            } else {
                mLaunchActivity = null
                mFloatingService?.recoverLive()
            }
        }
    }

    /**
     * 没有参数直接关闭小窗
     */
    fun onDestroyed() {
        onDestroyed(null, null)
    }

    /**
     * 有参数是恢复前关闭
     */
    fun onDestroyed(liveType: Int?, roomId: String? = null) {
        CoroutineScopeManager.mainScope.launch {
            mFloatingViewTouchListener = null
            removeFloatingWindow()

            mFloatingService?.let {
                it.onDestroyed(liveType, roomId)
                mFloatingService = null
            }
        }
    }

    private fun removeFloatingWindow() {
        mFloatView?.let {
            mWindowManager?.removeView(it)
            mFloatView = null
        }
    }

}
